import { checkType, randomNum } from "../share/util";

const reg_onClick = /onClick\=\"(.*?)\"/g;
const reg_fnName = /^(.*?)\(/;
const reg_arg = /\((.*?)\)/;
/**
 * {
 * flag:随机数
 * handler:事件处理字符串
 * type:click
 * }
 * @param {*}
 */
const eventPool = []; // 存放事件
export function eventFormat(template) {
  template = template.replace(reg_onClick, (node, key) => {
    const _flag = randomNum();
    eventPool.push({
      flag: _flag,
      handler: key.trim(),
      type: "click",
    });
    return `data-dom="${_flag}"`;
  });
  return template;
}

export function bindEvent(methods) {
  const allElements = document.getElementsByTagName("*");
  let oItem = null;
  let _flag = 0;
  eventPool.forEach((it) => {
    for (let i = 0; i < allElements.length; i++) {
      oItem = allElements[i];
      _flag = parseInt(oItem.dataset.dom);
      if (it.flag === _flag) {
        oItem.addEventListener(
          it.type,
          () => {
            const fnName = it.handler.match(reg_fnName)[1];
            const arg = checkType(it.handler.match(reg_arg)[1]);
            methods[fnName](arg);
          },
          false
        );
      }
    }
  });
}
